import 'package:flutter/material.dart';

class MyGetSizePage extends StatefulWidget {
  const MyGetSizePage({Key? key}) : super(key: key);

  @override
  State<MyGetSizePage> createState() => _MyGetSizePageState();
}

class _MyGetSizePageState extends State<MyGetSizePage> {
  List<String> books = ['《呐喊》', '《彷徨》', '《朝花夕拾》'];

  late String bookInfo;

  ValueNotifier<String> bookInfoNotifier = ValueNotifier('');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Align(
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 100),
              child: Wrap(
                spacing: 10,
                children: books.map((book) => createItem(book)).toList(),
              ),
            ),
            ValueListenableBuilder(
              valueListenable: bookInfoNotifier,
              builder: (context, value, child) => Text('点击书本展示书本位置信息：$value'),
            ),
            const MySizeBox(),
          ],
        ),
      ),
    );
  }

  Widget createItem(String book) {
    return Builder(builder: (context) {
      return GestureDetector(
        onTap: () => getBookLocalInfo(context),
        child: Container(
          padding: const EdgeInsets.all(16),
          child: Text(book),
          color: Colors.redAccent,
        ),
      );
    });
  }

  void getBookLocalInfo(BuildContext context) {
    //这里传入的context是为了context （rendObjectElement）方便读取 renderObject信息，如果拿根部的context读取wrap中每本书的renderObject将很困难
    final bookRenderObject = context.findRenderObject();
    if (bookRenderObject != null && bookRenderObject is RenderBox) {
      bookInfoNotifier.value =
          '当前书本的宽高信息是：${bookRenderObject.size},当前书本距离屏幕左上角坐标偏移量为${bookRenderObject.localToGlobal(Offset.zero)}';
    }
  }
}

class MySizeBox extends StatelessWidget {
  const MySizeBox({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => printInfo(context),
      child: SizedBox(
        width: 50,
        height: 50,
        child: Container(
          color: Colors.blue,
          child: const Text('点我获取信息'),
        ),
      ),
    );
  }

  void printInfo(BuildContext context) {
    final renderObject = context.findRenderObject();
    print('当前context对象的运行时类型是${context.runtimeType},因为不是renderObjectElement类型，'
        '所以element.find会查找子类首个renderObjectElement对象来获取renderObject,'
        '因为只有renderObjectElement才会持有渲染对象renderObject');
    if (renderObject != null && renderObject is RenderBox) {
      print('蓝色方块的尺寸为  宽:${renderObject.size.width},高:${renderObject.size.height}');
      print('相对屏幕左上角的偏移量为: ${renderObject.localToGlobal(Offset.zero)}');
    }
  }
}
